using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace SUnit.Core
{
    /// <summary>
    /// Clase utilizada para generar un "summary" de los resultados de los tests
    /// </summary>
    public class SummaryGenerator
    {
        private List<TestInfo> _tests = new List<TestInfo>();
        private List<TestResult> _results = new List<TestResult>();

        public SummaryGenerator()
        {
        }

        public void AddResult(TestInfo test, TestResult result)
        {
            _tests.Add(test);
            _results.Add(result);
        }

        public XmlDocument ExportResults()
        {
            Results results = new Results(_tests.Count);
            for (int i = 0; i < _tests.Count; i++)
            {
                Result res = new Result(_tests[i], _results[i]);
                results.SetResult(i, res);
            }

            //Serializamos el objeto de resultado
            MemoryStream ms = new MemoryStream();            
            XmlSerializer serializer = new XmlSerializer(typeof(Results));
            serializer.Serialize(ms, results);

            //Obtenemos el XML a partir del stream            
            ms.Position = (long)SeekOrigin.Begin;
            XmlDocument doc = new XmlDocument();
            doc.Load(ms);
            ms.Close();

            return doc;
        }
    }

    [Serializable]
    [XmlRoot(ElementName="Summary")]
    public class Results
    {
        private Result[] _results;

        public Results()
        {
        }

        public Results(int count)
        {
            _results = new Result[count];
        }

        [XmlElement(ElementName="TestResults")]
        public Result[] ResultsCollection
        {
            get { return _results; }
            set { _results = value; }
        }

        public void SetResult(int index, Result res)
        {
            _results[index] = res;
        }
    }

    [Serializable]
    [XmlRoot(ElementName="TestResult")]
    public class Result
    {
        private string _testName;
        private ResultState _result;
        private string _message;

        public Result()
        {
        }

        public Result(TestInfo test, TestResult result)
        {
            _testName = test.Name;
            _result = result.ResultState;
            _message = result.Message;
        }

        public string TestName
        {
            get { return _testName; }
            set { _testName = value; }
        }

        public ResultState ResultState
        {
            get { return _result; }
            set { _result = value; }
        }

        public string Message
        {
            get { return _message; }
            set { _message = value; }
        }
    }
}
